var categoriesCount = 0;



var TodoItems = function () {
    var self = this;

    this.storage = new TodoStorage();

    this.storage.afterItemAdded = function () {
        self.render();
    }

    this.storage.afterSetItems = function () {
        self.render();
    }

    this.storage.onSyncError = function (data, textStatus, jqXHR) {
        if (textStatus != 'abort' && jqXHR != 'abort' && !(textStatus == 'error' && jqXHR == '')) {
            clearTimeout(this.syncTimer);

            /*
             var getTime = function(time, count) {
             if(count > 0) {
             return getTime(time * 2, count - 1);
             } else {
             return time;
             }
             };

             var time = getTime(5, self.storage.syncErrorsCount - 1 );

             self.showSyncMsg(time > 60 ? 60 : time, function () {
             self.storage.sync();
             });
             */

            var time = 5;

            time = time * self.storage.syncErrorsCount;

            self.showSyncMsg(time > 30 ? 30 : time, function () {
                self.storage.sync();
            });
        }
    }

    this.storage.onSyncSuccessful = function () {
        clearTimeout(self.syncMsgTimer);
        $('#notification').fadeOut(400, function () {
            $(this).empty();
        });
    }

    this.config = {
        itemsContainer: '#lists',
        mainTpl: _.template($('#main-template').html()),
        categoryTpl: _.template($('#category-template').html()),
        itemTpl: _.template($('#item-template').html())
    };

    /**
     *
     */
    this.render = function () {
        var categories = this.storage.categories;

        $(this.config.itemsContainer).html(this.config.mainTpl({
            categories: categories,
            renderCategory: self.renderCategory
        }));

        this.afterRender();
    }

    this.renderCategory = function (params) {
        params = $.extend(params, {
            renderItem: self.renderItem,
            filterItems: self.storage.filterItems
        })

        return self.config.categoryTpl(params);
    }

    this.renderItem = function (params) {
        return self.config.itemTpl(params);
    }

    /**
     *
     */
    this.afterRender = function () {
        this.initDragAndDrop();
    }

    /**
     *
     */
    this.bindEvents = function () {
        var self = this;

        /**
         * Focus


         $(document).on('keydown', 'body', function (e) {
            if (e.keyCode == 9) {
                $('#newitem textarea').focus();
            }
        }); */


        /**
         * Add new item
         */
        $(document).on('keydown', '#newitem textarea', function (e) {
            if (e.keyCode == 13) {
                // c3 start
                var value = $(this).val();

                if (value.indexOf('@') === 0)
                    self.storage.addCategory(value.replace(/(<([^>]+)>)/ig, ""));
                else
                    self.storage.addItem(value.replace(/(<([^>]+)>)/ig, ""));

                // c3 end
                // self.storage.addItem($(this).val().replace(/(<([^>]+)>)/ig, ""));
                $(this).val('').blur();
            }

            if (e.keyCode == 27) {
                $(this).val('').blur();
            }
        });

        new Todo.Item();

        /**
         * Start editing category
         */
        $(document).on('dblclick', 'li.category > p', function () {
            return;

            $('#return').html($(this).parent('li.title').find('textarea').val().replace(/(<([^>]+)>)/ig, ""));

            var parent = $(this).parent('li.title');

            $(parent).addClass('editing');
            //$(this).replaceWith('<textarea class="edit" rows="1">' + $(this).text().replace(/(<([^>]+)>)/ig, "") + '</textarea>').find('textarea');

            EnableSync = 0;

            $(parent).find('textarea:visible').focus().select();

        });

        /**
         * Textarea Resize
         */
        $(document).on('keydown keyup focus', '#name, #lists .item.editing textarea', function () {
            $(this).css('width', $('#clone').width() + 30);
            $(this).css('height', $('#clone').height());
        });

        $(document).on('keydown keyup', '#name', function () {
            if ($('#name').val() != '') {
                $('#mic').css('opacity', 0);
                $('.clear').show();
            } else {
                $('#mic').css('opacity', 1);
                $('.clear').hide();
            }
        });

        $(document).on('webkitspeechchange', '#mic', function (e) {
            var result = $(this).val();
            $(this).val('');

            $('#name').val(result).focus();

            $(this).css('opacity', 0);
            $('.clear').show();
        });

        // Hide Mic
        /**
         * Clear Textarea
         */
        $(document).on('click', '.clear', function () {
            $(this).hide();
            $('#mic').val('').css('opacity', 1);
            $('#newitem textarea').val('').focus();
        });

        function itemEdit() {
            var element = '#lists textarea:visible';
            $item = $(element).parents('li.item');
            var itemId = $item.attr('data-internal-id');

            if (itemId) {
                if ($(element).val() == '') {
                    $item.trigger('delete.Todo');
                    //self.storage.updateItem(itemId, 'delete');
                } else if ($(element).val().replace(/(<([^>]+)>)/ig, "") != $('#return').html()) {
                    $item.trigger('rename.Todo');
                    //self.storage.updateItem(itemId, 'edit', $(element).val().replace(/(<([^>]+)>)/ig, ""));
                } else {

                    //$(element).parents('li').removeClass('editing');
                }
            }
        }

        function categoryEdit() {
            var element = '.title textarea:visible';
            var itemId = $(element).parents('li').attr('data-iternal-id');

            if (itemId) {
                if ($(element).val() == '') {
                    self.storage.updateCategory(itemId, 'delete');
                } else if ($(element).val().replace(/(<([^>]+)>)/ig, "") != $('#return').html()) {
                    self.storage.updateCategory(itemId, 'edit', $(element).val().replace(/(<([^>]+)>)/ig, ""));
                } else {
                    //$(element).parents('li').removeClass('editing');
                }
            }
        }

        $(document).on('click', '#notification .resync-link', function (e) {
            e.preventDefault();
            self.syncStorage();
        })
    }

    this.init = function () {
        self.bindEvents();

        self.storage.setItems(getFromStorage());
        self.storage.setCategories(getCategoriesFromStorage());
        //alert(self.storage.categories);
    };

    this.syncMsgTimer = null;

    this.showSyncMsg = function (time, callback) {
        var self = this;

        time = parseInt(time);

        clearTimeout(self.syncMsgTimer);

        var template = _.template($('#notification-error-sync').html());
        $('#notification').html(template({timeLeft: time}));
        if ($('#notification').is(':hidden')) {
            $('#notification').fadeIn(450);
        }

        if (time > 0) {
            self.syncMsgTimer = setTimeout(function () {
                self.showSyncMsg(time - 1, callback);
            }, 1000);
        } else if (typeof callback == "function") {
            callback();
        }
    }

    this.syncStorage = function () {
        var self = this;

        self.showSyncMsg(0, function () {
            self.storage.sync();
        });
    }


    this.initDragAndDrop = function () {
        /*
         var elements = '#dd0';
         for (i = 1; i <= categoriesCount; i++) {
         elements += ',#dd' + i;
         }
         $(elements).sortable({
         connectWith: ".items",
         stop: this.reorginizeDataAfterSort
         }).disableSelection();
         */

        //*/
        $('.category ul.other').sortable({
            items: "li",
            helper: "clone",
            handle: ".drag",
            cursor: "move",
            placeholder: "drag-to",
            connectWith: ".other",
            opacity: 0.5,
            start: function(event, ui) {
                $('#lists .category > ul.other').addClass('dropable');
            },
            stop: function() {
                $('#lists .category > ul').removeClass('dropable');
            } //this.reorginizeDataAfterSort
        }).disableSelection();
        /*/

        $('#lists').sortable({
            items: "li.category:not(.main)",
            handle: "> .title > .drag",
            cursor: "move",
            stop: function() {} //this.reorginizeDataAfterSort
        }).disableSelection();
        //*/

        // alert(elements);

    }

    this.reorginizeDataAfterSort = function (evt, ui) {
        EnableSync = 0;

        var items = [];
        var categories = [];

        // parse items for default category
        $('li.ui-drag-disabled ul.items li').each(function (index, value) {
            id = $(this).attr('data-item-id');
            name = $(this).find('span').html();

            items.push({
                id: id,
                name: name,
                completed: false,
                deleted: false,
                category: 'default',
                category_id: null,
                position: index

            });

        });
        // parse categories
        $('li.title').each(function (ind, val) {
            category_id = $(this).attr('data-item-id');
            name = $(this).find('span').html();
            categories.push({
                id: category_id,
                name: name,
                position: ind,
                deleted: false
            });
            // in each category parse items

            $(this).find('ul.items li').each(function (i, v) {
                classname = $(this).attr('class');
                if (classname != 'placeholder') {

                    item_id = $(this).attr('data-item-id');
                    name = $(this).find('span').html();

                    items.push({
                        id: item_id,
                        name: name,
                        completed: false,
                        deleted: false,
                        category: 'default',
                        category_id: category_id,
                        position: i

                    });
                }
            });

        });

        self.storage.setCategories(categories);
        self.storage.setItems(items);

        EnableSync = 1;

        self.storage.sync();
        /*/
         report = ''; // test code for debugging

         _.each(items, function (val, ind) {

         if (val.category_id == 0)

         report += val.name + '=' + val.category_id + "\n";
         });

         _.each(categories, function (val, ind) {
         report += val.name + '(cat)' + val.id + "\n";
         _.each(items, function (v, i) {
         if (val.id == v.category_id)
         report += "\t" + v.name + '=' + v.position + "\n";

         });
         });

         alert(report);
         //*/
    }

    this.init();
};

// Speech Input Fields
function transcribe(words) {

}

// c3 start
function isCategory(name) {
    if (name.indexOf('@') === 0)
        return true;
}

function existItemInCategory(category_id, items) {
    _.each(items, function (i, k) {
        if (i.category_id == category_id)
            return true;
    });

    return false;
}
// c3 end